package router

import (
	"bufio"
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	logg "log"
	"net/http"
	"os"
	"time"

	"../mode"
	"github.com/tungyao/cedar"
)

type Wechat cedar.AutoRegister

// 首页的推荐
//
func (*Wechat) Get_WechatIndex(w http.ResponseWriter, r *http.Request, co *cedar.Core) {
	co.Json().Success(QueryRows(w, r, 1))
}
func (*Wechat) Get_WechatDetail(w http.ResponseWriter, r *http.Request, co *cedar.Core) {
	// 增加缓存
	if row := P.Get([]byte("we_" + r.URL.Query().Get("data"))); row != nil {
		co.Json().Success(row.(mode.ArticleData))
		return
	}
	row := QueryRows(w, r, 1)
	P.Set([]byte("we_"+r.URL.Query().Get("data")), row, 0)
	co.Json().Success(row)
}

const APPID = "13123123"
const Secret = "123123132"

var ACCESS = "36_VBFBz_tVELzL5BxZl0IDrbZFw1AYJP9WhQzg13aQDv0GzU4tAOpRKYad57VLfWkvxedLni6qDVmPVz_MJfzc_kUdQIeyUJcUi4xn8q1b2MW0QAAsczKIGihjUC00p6QF_gFCGTaX-0x5K0suEVLaAAALCS"

type AccessTokens struct {
	AccessToken string `json:"access_token"`
	ExpiresIn   int    `json:"expires_in"`
	Errcode     int    `json:"errcode"`
	Errmsg      string `json:"errmsg"`
}

func init() {
	at, b := loadAccess()
	if b {
		ACCESS = at.AccessToken
	}
	go func() {
		ticker := time.NewTicker(time.Minute * 30 * 3) // 90分钟
		logg.Println("启动计时器")
		for _ = range ticker.C {
			at, b := loadAccess()
			if log != nil {
				log.Println("更新access token")
			}
			if b {
				ACCESS = at.AccessToken
			} else {
				ticker.Stop()
			}
		}
	}()
}
func loadAccess() (*AccessTokens, bool) {
	rep, err := http.Get(fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", APPID, Secret))
	if err != nil {
		log.Println(err)
		return nil, false
	}
	data := make([]byte, 1024)
	n, _ := rep.Body.Read(data)
	at := &AccessTokens{}
	err = json.Unmarshal(data[:n], at)
	if err != nil {
		log.Println(err)
		return at, false
	}
	return at, true
}
func loadQr(id string) {
	if fs, err := os.Open("./static/qr/wechat/" + id + ".jpg"); err != nil {
		if fs != nil {
			fs.Close()
		}
		p := &os.PathError{
			Op:   "open",
			Path: "./static/qr/wechat/" + id + ".jpg",
			Err:  errors.New("The system cannot find the file specified."),
		}
		if err.Error() != p.Error() {
			return
		}
		dataS := map[string]interface{}{
			"access_token": ACCESS,
			"path":         "/pages/detail/detail?id=" + id,
			"width":        500,
		}
		data, _ := json.Marshal(dataS)

		rep, err := http.Post(fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=%s", ACCESS), "application/json", bytes.NewReader(data))
		if err != nil {
			fmt.Println(err)
			return
		}
		fs, err := os.OpenFile("./static/qr/wechat/"+id+".jpg", os.O_CREATE|os.O_WRONLY, 666)
		if err != nil {
			log.Panicln(err)
		}
		_, err = fs.Seek(0, 0)
		if err != nil {
			log.Panicln(err)
		}
		reader := bufio.NewReader(rep.Body)
		defer rep.Body.Close()
		_, err = reader.WriteTo(fs)
		if err != nil {
			log.Println(err)
		}
		fmt.Println(id)
		fs.Close()
	} else {
		if fs != nil {
			fs.Close()
		}
	}

}
